import { login, getInfo, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const rememberMe = userInfo.rememberMe
      /* var res = {}
      var yf = {
        'user': {
          'id': 102,
          'username': 'yf',
          'nickName': '申请人',
          'sex': '男',
          'avatar': null,
          'email': '123@qq.com',
          'phone': '13857263311',
          'dept': '研发部',
          'job': '软件测试',
          'enabled': true,
          'createTime': 1600773111000,
          'roles': [
            '部分'
          ]
        },
        'token': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ5ZiIsImF1dGgiOiLpg6jliIYiLCJleHAiOjE2MDA5NDk2MTV9.ik5rifhh32BcvZYcjqweVxFRxCKW4af4mCd22FLRrr67H4PSCTvkOKIXHBc9lB_mTfCAplYHiiPmI7aNVfIbHA'
      }
      var yfgly = { 'user': { 'id': 103, 'username': 'yfjl', 'nickName': '审批人', 'sex': '男', 'avatar': null, 'email': '456@qq.com', 'phone': '17863746258', 'dept': '研发部', 'job': '产品经理', 'enabled': true, 'createTime': 1600773152000, 'roles': ['部分'] }, 'token': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ5ZmpsIiwiYXV0aCI6IumDqOWIhiIsImV4cCI6MTYwMTAyMTM5N30.HigdT6kGxld5TmCrcSUvINWVyMUL62LfDMeaFvB7aazVH-fL-gTTGVJRl86TYdCEUSso0N9DKCC07cXh1y5L9w' }
      var admin = { 'user': { 'id': 1, 'username': 'admin', 'nickName': '管理员', 'sex': '男', 'avatar': null, 'email': 'junjie.miao@goupwith.com', 'phone': '18888888888', 'dept': '研发部', 'job': '全栈开发', 'enabled': true, 'createTime': 1534986716000, 'roles': ['roles:add', 'user:list', 'user:add', 'menu:del', 'roles:del', 'admin', 'menu:edit', 'menu:list', 'user:del', 'roles:list', 'dict:add', 'menu:add', 'user:edit', 'roles:edit', 'dict:del', 'dict:list', 'dict:edit'] }, 'token': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJyb2xlczphZGQsdXNlcjpsaXN0LHVzZXI6YWRkLG1lbnU6ZGVsLHJvbGVzOmRlbCxhZG1pbixtZW51OmVkaXQsbWVudTpsaXN0LHVzZXI6ZGVsLHJvbGVzOmxpc3QsZGljdDphZGQsbWVudTphZGQsdXNlcjplZGl0LHJvbGVzOmVkaXQsZGljdDpkZWwsZGljdDpsaXN0LGRpY3Q6ZWRpdCIsImV4cCI6MTYwMTAyMTczOH0.V_2TiJAkBLq8ODVf_hYegumqs4qPitx5mO3sgeBxhJmux4UFRWsa9M3P8RLiymkenrLt2Qv3yWbrZUGZCy6QFw' }
      if (userInfo.username == 'yf') {
        res = yf
      } else if (userInfo.username == 'yfjl') {
        res = yfgly
      } else {
        res = admin
      }
      setToken(res.token, rememberMe)
      commit('SET_TOKEN', res.token)
      setUserInfo(res.user, commit)
      // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
      commit('SET_LOAD_MENUS', true)*/
      // resolve()
      return new Promise((resolve, reject) => {
        login(userInfo.username, userInfo.password, userInfo.code, userInfo.uuid).then(res => {
          setToken(res.token, rememberMe)
          commit('SET_TOKEN', res.token)
          setUserInfo(res.user, commit)
          // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
          commit('SET_LOAD_MENUS', true)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          setUserInfo(res, commit)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        // logOut(commit)
        logout().then(res => {
          logOut(commit)
          resolve()
        }).catch(error => {
          logOut(commit)
          reject(error)
        })
      })
    },

    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_LOAD_MENUS', false)
      })
    }
  }
}

export const logOut = (commit) => {
  commit('SET_TOKEN', '')
  commit('SET_ROLES', [])
  removeToken()
}

export const setUserInfo = (res, commit) => {
  // console.log('res', res)
  // 如果没有任何权限，则赋予一个默认的权限，避免请求死循环
  if (res.roles.length === 0) {
    commit('SET_ROLES', ['ROLE_SYSTEM_DEFAULT'])
  } else {
    commit('SET_ROLES', res.roles)
  }
  commit('SET_USER', res)
}

export default user
